package hot;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lakersUp
 * @Classname   括号生成
 * @Description     dfs,回溯
 * @Date 2022/3/8 18:47
 * @Version 1.0
 */
public class Hot22generateParenthesis {
    List<String> list=new ArrayList<>();
    public List<String> generateParenthesis(int n) {
        dfs(n,new StringBuffer(),0,0);
        return list;
    }

    private void dfs(int n, StringBuffer sb, int left, int right) {
        if(right==n){
            list.add(sb.toString());
            return;
        }
        if(left<n){
            sb.append('(');
            dfs(n, sb, left+1, right);
            sb.deleteCharAt(sb.length()-1);
        }
        if(right<left){
            sb.append(')');
            dfs(n, sb, left, right+1);
            sb.deleteCharAt(sb.length()-1);
        }
    }
}
